package com.roy.workbench.jsp.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.roy.workbench.bookmark.domain.Bookmark;
import com.roy.workbench.bookmark.service.BookmarkService;
import com.roy.workbench.bookmark.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.Map;

/**
 * Created by admin on 17-12-25.
 */
@Controller
public class IndexController {
    @Autowired
    private BookmarkService bookmarkService;
    @Autowired
    private CatalogService catalogService;

    @Value("${application.message:Hello World}")
    private String message = "Hello World";

    @GetMapping(value = "/account")
    public String index(Map<String, Object> model) {
        model.put("time", new Date());
        model.put("message", "dfdfdfdfdf椎间盘买个");
        System.out.println("this is index page....");
//        return new ModelAndView("index");
        return "account";
    }

    @GetMapping("/")
    public String welcome(Map<String, Object> model) throws JsonProcessingException {
        model.put("time", new Date());
        model.put("message", this.message);

        PageRequest pageRequest = new PageRequest(0,20);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(catalogService.query(pageRequest).getContent());
        model.put("datastr", json);
        model.put("data", catalogService.query(pageRequest).getContent());
        return "index";
    }

    @PostMapping(path = "/createBookmark", consumes = "application/json")
    @ResponseBody
    public ResponseEntity<Bookmark> create(@RequestBody Bookmark bookmark){

        bookmark.setCreateTime(new Date());
        bookmark.setUpdateTime(new Date());
        Bookmark bookmark1 = bookmarkService.save(bookmark);

        return new ResponseEntity(bookmark1, HttpStatus.CREATED);
    }

    @RequestMapping("/foo")
    public String foo(Map<String, Object> model) {
        throw new RuntimeException("Foo");
    }

    @GetMapping(path = "/ss",produces = "application/json")
    @ResponseBody
    public String error(){
        return "errollllllllllllllllllll";
    }
}
